////<!--访客车辆信息-->
import { deepCopyObj } from '../../../assets/js/help.js';
export default {
  data() {
    var validateVisitFromTo = (rule, value, callback) => {
      if (value == null || value == '' || value == ',') {
        return callback(new Error('请选择来访时间'));
      }
      callback();
    };
    var validateParkJson = (rule, value, callback) => {
      var self = this;
      if (!self.mouthTicketData.dataSave.parkJson.length) {
        return callback(new Error('请选择支持的停车场'));
      }
      for (var i = 0; i < self.mouthTicketData.dataSave.parkJson.length; i++) {
        var parkJsonItem = self.mouthTicketData.dataSave.parkJson[i];

        if (!parkJsonItem.parkVipTypeId) {
          return callback(new Error('请选择停车场的VIP类型'));
        }
      }
      callback();
    };
    return {
      selectAllItemsStatus: '0',
      itemsNum: 0,
      itemsKeyName: '',
      actionStatus: 'add',
      specialCarTypeConfigName: '',
      specialCarTypeConfigList: [],
      syncDetailModal: {
        theadsInfo: [
          { index: 0, isShow: false, prop: 'parkName', text: '支持停车场', minWidth: 120 },
          { index: 1, isShow: false, prop: 'customVipName', text: '绑定VIP类型', minWidth: 120 },
          { index: 2, isShow: false, prop: 'sendTime', text: '同步时间', minWidth: 170 },
          { index: 3, isShow: false, prop: 'sendStatus', text: '同步结果', minWidth: 120 },
          { index: 4, isShow: false, prop: 'respDesc', text: '失败原因', minWidth: 220 },
          { index: 5, isShow: false, prop: 'operate', text: '操作', minWidth: 120 }
        ],
        syncDetailList: []
      },
      supportParkList: [],
      supportPark: {
        theadsInfo: [
          { index: 0, isShow: false, prop: 'parkName', text: '停车场', minWidth: 120 },
          { index: 1, isShow: false, prop: 'parkVipTypeStr', text: '绑定VIP类型', minWidth: 120 }
        ]
      },
      mouthTicketData: {
        isShowSpecialCarType: false, //特殊车辆类型名称下拉框
        isCreate: true,
        isAble: true,
        dataSave: {
          //用于保存时发送到后台的数据
          specialCarTypeConfigId: '',
          id: '',
          carLicenseNumber: '',
          owner: '',
          ownerPhone: '',
          visitReason: '',
          remark1: '',
          remark2: '',
          remark3: '',
          visitFromTo: '',
          parkJson: [] //每条记录都记录 停车场的ID和对应的VIP类型的关系
        }
      },
      entity: {
        specialCarTypeConfigId: '',
        id: null,
        carLicenseNumber: '',
        owner: '',
        ownerPhone: '',
        visitReason: '',
        remark1: '',
        remark2: '',
        remark3: '',
        parkList: [],
        availableParkCodeList: [],
        visitFromTo: ''
      },
      tableData: {
        ParkNameList: [], //用于请求VIP类型的列表的车场name参数
        parkIdList: [], //用于请求VIP类型的列表的车场ID参数
        parkVipTypeId: [], //当点击编辑按钮时  显示上一次保存的对应的VIP类型
        parkItems: [] //通过停车场的ID请求到的停车场对应的VIP类型的列表
      },
      rules: {
        specialCarTypeConfigId: [
          {
            required: true,
            message: '特殊车辆类型不能为空',
            trigger: 'change'
          }
        ],
        ticketName: [
          { required: true, message: '月票名称不能为空', trigger: 'change' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'change' }
        ],
        carLicenseNumber: [
          { required: true, message: '车牌号码不能为空', trigger: 'change' },
          { max: 8, message: '最多8 个字符', trigger: 'change' }
        ],
        owner: [
          { required: true, message: '车主姓名不能为空', trigger: 'change' },
          { max: 10, message: '最多10 个字符', trigger: 'change' }
        ],
        ownerPhone: [
          { required: true, message: '电话号码不能为空', trigger: 'change' },
          {
            validator(r, v, b) {
              /^1\d{10}$/.test(v) ? b() : b(new Error('手机格式不符合'));
            },
            trigger: 'change'
          }
        ],
        visitReason: [
          { required: true, message: '来访原因不能为空', trigger: 'change' },
          { max: 100, message: '最多100 个字符', trigger: 'change' }
        ],
        remark1: [{ max: 100, message: '最多100 个字符', trigger: 'change' }],
        remark2: [{ max: 100, message: '最多100 个字符', trigger: 'change' }],
        remark3: [{ max: 100, message: '最多100 个字符', trigger: 'change' }],
        visitFromTo: [
          { type: 'array', required: true, message: '来访时段不能为空', trigger: 'change' },
          { validator: validateVisitFromTo, trigger: 'change' }
        ],
        parkJson: [
          { type: 'array', required: true, message: '支持停车场不能为空', trigger: 'change' },
          { validator: validateParkJson, trigger: 'change' }
        ]
      },
      remarkChunkShow: false //多个备注块是否显示
    };
  },
  watch: {
    'mouthTicketData.dataSave.parkJson': function(newMouthTicketData) {
      if (this.$refs.ticketForm) {
        this.$refs.ticketForm.validateField('parkJson');
      }
    }
  },
  created() {
    toBase64(this);
    function toBase64(vm) {
      $(document).on('change', '#traderSelling input', function() {
        var file = this.files[0];
        var reader = new FileReader();
        if (!/image\/\w+/.test(file.type)) {
          vm.showToast('请确保文件为图像类型', 2);
          $('#traderSelling input').val('');
          return false;
        }
        vm.mouthTicketData.dataSave.sellingPicName = file.name;
        reader.readAsDataURL(file);
        reader.onload = function(e) {
          var res = e.target.result.replace('data:image/png;base64,', '');
          res = res.replace('data:image/jpg;base64,', '');
          res = res.replace('data:image/jpeg;base64,', '');
          vm.mouthTicketData.dataSave.sellingPic = res;
        };
      });
      $(document).on('change', '#traderSellout input', function() {
        var file = this.files[0];
        var reader = new FileReader();
        if (!/image\/\w+/.test(file.type)) {
          vm.showToast('请确保文件为图像类型', 2);
          $('#traderSellout input').val('');
          return false;
        }
        vm.mouthTicketData.dataSave.selloutPicName = file.name;
        reader.readAsDataURL(file);
        reader.onload = function(e) {
          var res = e.target.result.replace('data:image/png;base64,', '');
          res = res.replace('data:image/jpg;base64,', '');
          res = res.replace('data:image/jpeg;base64,', '');
          vm.mouthTicketData.dataSave.selloutPic = res;
        };
      });
    }
  },
  methods: {
    // 添加访客类型-弹框
    addSpecialCarType() {
      this.$refs.specialCarTypeCom.createConfig('添加访客类型', 1);
    },
    // 查看访客类型
    checkVisitorType(rowData) {
      let params = {};
      params.specialCarTypeConfigId =
        rowData && rowData.specialCarTypeConfigId
          ? rowData.specialCarTypeConfigId
          : this.mouthTicketData.dataSave.specialCarTypeConfigId;
        if(!params.specialCarTypeConfigId){
          this.showToast('请先选择类型',0,1500);
          return;
        }
      this.$refs.specialCarTypeCom.checkSpecialCarType(params, 1);
    },
    getDefaultParams(){//获取不能缺少的默认的参数
      let self = this;
      let searchParams = self.searchParams,
          searchList = self.searchList,
          result = {};
          var visitTimeFromTo;
          for (var key in searchList) {
              if (searchList.hasOwnProperty(key)) {
                  var item = searchList[key];
                  console.log(item);
                  if(item.name=='visitTimeFromTo'){
                    visitTimeFromTo = item;
                  }
              }
          }
      return result;
    },
    getList() {
      let params = $.extend({}, this.searchParams, this.otherParams,this.getDefaultParams());
      this.getMonthTicketManageList(params);
    },
    getMonthTicketManageList(aparams) {
      let self = this,
        params = {
          page: this.pageNumber,
          rp: this.pageSize
        };
      params = $.extend({}, params, aparams);
      API.park.GetParkVisitorlistData(params).then(
        res => {
          let data = res.data,
            list = data.rows;
          self.tbodysInfo = list;
          self.total = data.total;
        },
        err => {}
      );
    },
    resetMouthData() {
      this.mouthTicketData.dataSave = {
        specialCarTypeConfigId: '',
        id: '',
        carLicenseNumber: '',
        owner: '',
        ownerPhone: '',
        visitReason: '',
        remark1: '',
        remark2: '',
        remark3: '',
        visitFromTo: '',
        parkJson: []
      };
      this.tableData = {
        ParkNameList: [],
        parkIdList: [],
        parkVipTypeId: [],
        parkItems: []
      };
      this.entity.parkList = [];
    },
    createTicket: function(type) {
      var self = this;
      self.traderstatus = 'new';
      self.actionStatus = 'add';
      self.remarkChunkShow = false;
      self.resetMouthData();
      self.getVisitorConfigList();
      self.toOpenModal('createVisitorModal');
    },
    getVisitorConfigList(type) {
      var self = this;
      API.fetchGet('/park/parkVisitorlist/getVisitorConfigList.do',{}).then(
        res => {
          let data = res.data;
          self.specialCarTypeConfigList = data;
          if(type && type=='addNew'){
            self.mouthTicketData.dataSave.specialCarTypeConfigId = self.specialCarTypeConfigList[0].id
          }
        },
        err => {}
      );
    },

    supportParkShowModal(row) {
      //兼容旧版
      this.supportParkList = [];
      if (row.sysVersion <= 2.3) {
        this.supportParkList = row.parkList;
        this.toOpenModal('supportParkModal', 1);
      } else {
        //新版
        this.initChannelTree(null, null, 'ParkTree', row);
        this.toOpenModal('selectParkModal', 1);
      }
    },
    searchItems(treeName) {
      var self = this;
      var treeObj = $.fn.zTree.getZTreeObj(treeName);
      var nodes = treeObj.getNodesByParamFuzzy('name', self.itemsKeyName, null);
      treeObj.cancelSelectedNode();
      nodes.forEach(function(node) {
        treeObj.selectNode(node, true, false);
      }, this);
    },
    selectAllItems(treeName) {
      var self = this;
      var treeObj = $.fn.zTree.getZTreeObj(treeName);
      console.log(self.selectAllItemsStatus);
      if (self.selectAllItemsStatus == '0') {
        treeObj.checkAllNodes(true);
      } else {
        treeObj.checkAllNodes(false);
      }
      self.setItemNums(treeName);
    },
    setItemNums(treeName) {
      var self = this;
      var treeObj = $.fn.zTree.getZTreeObj(treeName);
      var nodes = treeObj.getCheckedNodes(true);
      var itemsNum_ = 0;
      nodes.forEach(function(node) {
        if (!node.isParent && node.channelSeq) {
          itemsNum_++;
        }
      }, this);
      self.itemsNum = itemsNum_;
    },
    //==========================================
    initChannelTree(parkId, vipTypeId, treeName, rowParam) {
      var self = this;
      self.itemsNum = 0;
      var params, fetchUrl;
      if (rowParam) {
        params = {
          id: rowParam.specialCarTypeConfigId
        };
        fetchUrl = '/park/parkVisitorlist/getConfigParkChannels.do';
      }
      API.fetchPost(fetchUrl, params).then(
        res => {
          if (res.data.length == 0) {
            return;
          }
          if (res.status == 1) {
            //start..
            var data = res;
            if (data != null) {
              var nodes = res.data;
              var settings = {
                check: {
                  enable: true,
                  autoCheckTrigger: true,
                  chkboxType: {
                    Y: 'ps',
                    N: 'ps'
                  }
                },
                data: {
                  key: {
                    checked: 'checked',
                    chkDisabled: true,
                    children: 'childrenList'
                  }
                },
                view: {
                  showIcon: false,
                  showLine: false
                },
                callback: {
                  onClick: function(event, treeId, treeNode) {
                    var treeObj = $.fn.zTree.getZTreeObj(treeName);
                    if (treeNode.checked) {
                      treeObj.checkNode(treeNode, false, false);
                    } else {
                      treeObj.checkNode(treeNode, true, false);
                    }
                    var channelSeqList = [];
                    var checkedNodes = treeObj.getCheckedNodes(true);
                    for (var i = 0; i < checkedNodes.length; i++) {
                      channelSeqList.push(checkedNodes[i].channelSeq);
                    }
                    self.$set(self.vipTypeData, 'channelSeqList', channelSeqList);
                  },
                  onCheck: function(event, treeId, treeNode) {
                    var treeObj = $.fn.zTree.getZTreeObj(treeName);
                    self.setItemNums(treeName);
                    //   var channelSeqList = [];
                    //   var checkedNodes = treeObj.getCheckedNodes(true);
                    //   for (var i = 0; i < checkedNodes.length; i++) {
                    //     channelSeqList.push(checkedNodes[i].channelSeq);
                    //   }
                    //   self.$set(self.vipTypeData, 'channelSeqList', channelSeqList);
                  }
                }
              };
              $.fn.zTree.destroy(treeName);
              $.fn.zTree.init($('#ParkTree'), settings, []);
              var treeObj = $.fn.zTree.getZTreeObj(treeName);
              // var nodes = treeObj.getNodes();
              // self.vipTypeData.channelAuthTree = nodes;
              console.log(nodes);
              treeObj.addNodes(null, 0, nodes);

              //勾选父节点的操作
              var temp_checkNodes = treeObj.getCheckedNodes();
              temp_checkNodes.forEach(function(t) {
                if (!t.hasChildren) {
                  treeObj.checkNode(t, true, true);
                }
              }, this);

              treeObj.expandAll(true);
            } else {
              self.showToast('该停车场没有配置通道', 2, 3000);
            }
            //end..
          } else {
            self.showToast(res.message, 2, 2000);
            return;
          }
        },
        err => {}
      );
    },
    //==========================================

    openSelectParkModal() {
      var _self = this;
      _self.toOpenModal('selectParkModal', 2);
      this.initParkTree('ParkTree');
    },
    initParkTree(treeId) {
      var _self = this;
      API.park.getParkTree({}).then(
        res => {
          //start..
          var data = res;
          if (data != null) {
            var nodes = data.data;
            var jsonStr = JSON.stringify(nodes);

            jsonStr = jsonStr.replace(/(\"isArea\"\:true\,)/g, '"isArea": true,"chkDisabled":true, "nocheck":true,');
            nodes = JSON.parse(jsonStr);
            var settings = {
              check: {
                enable: true,
                chkStyle: 'checkbox',
                radioType: 'all'
              },
              // data: {
              //     simpleData: {
              //         enable: true
              //     }
              // },
              view: {
                showIcon: false,
                showLine: false
              },
              callback: {
                onClick: function(event, treeId, treeNode) {
                  var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
                  treeObj.checkNode(treeNode, true, false);
                  if (treeNode.isArea) {
                    return;
                  }
                }
              }
            };
            $.fn.zTree.destroy('ParkTree');

            var treeObj = $.fn.zTree.init($('#ParkTree'), settings, nodes);
            var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
            console.log(nodes);
            for (var i = 0; i < _self.entity.parkList.length; i++) {
              var node = treeObj.getNodeByParam('value', _self.entity.parkList[i]);
              if (node) {
                if (node.getParentNode() && !node.getParentNode().open) {
                  treeObj.expandNode(node.getParentNode(), true, true, true);
                }
                treeObj.checkNode(node, true, true);
              }
            }
            treeObj.expandAll(true);
          } else {
            _self.showToast('暂时没有停车场可选', 2, 3000);
          }
          //end..
        },
        err => {}
      );
    },
    selectParkSure() {
      var self = this,
        nodes = [];
      var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
      nodes = treeObj.getCheckedNodes(true); // 获取tree被勾选的节点
      var parkList = new Array();
      // 初始化表格显示数据以及提交的表格参数
      self.tableData = {
        ParkNameList: [],
        parkIdList: [],
        parkVipTypeId: [],
        parkItems: []
      };
      self.mouthTicketData.dataSave.parkJson = [];
      for (var i = 0; i < nodes.length; i++) {
        if (!nodes[i].isArea) {
          parkList.push(nodes[i]);
        }
      }
      if (parkList.length <= 0) {
        self.showToast('请选择一个停车场', 0);
        return;
      }
      self.entity.parkList = [];
      for (var i = 0; i < parkList.length; i++) {
        self.entity.parkList.push(parkList[i].value);
        self.tableData.parkIdList.push(parkList[i].value);
        self.tableData.ParkNameList.push(parkList[i].name);
      }
      //console.log(self.tableData.parkIdList)
      //console.log(self.tableData.ParkNameList)
      self.closed('selectParkModal', 2);
      self.getParkItems();
    },
    getParkItems() {
      //循环请求每一个车场的VIP类型列表  如果是编辑的话  默认选中车场的VIP类型
      var self = this;
      var itemobj = {};
      var itemobjArr = [];
      var parkJson = {}; //表格每一行的的数据组成一个对象，，所有的行组成一个数组
      var parkJsonArr = []; //装parkJson对象的数组
      var param = {};
      var ParkNameList = self.tableData.ParkNameList;
      var parkIdList = self.tableData.parkIdList;
      for (var i = 0; i < parkIdList.length; i++) {
        itemobj = {};
        parkJson = {};
        param.parkId = parkIdList[i];
        $.ajax({
          type: 'get',
          url: '/mgr/monthTicketConfig/vipTypeList.do',
          data: param,
          cache: false,
          dataType: 'json',
          async: false,
          success: function(data) {
            if (data.data.length == 0) {
              self.showToast('已过滤不存在VIP类型的停车场', 0, 2000);
              return;
            }
            itemobj.ParkName = ParkNameList[i];
            itemobj.parkId = parkIdList[i];
            parkJson.parkId = parkIdList[i];
            parkJson.parkVipTypeId = self.tableData.parkVipTypeId[i] || ''; // 编辑时默认选中VIP类型
            parkJsonArr.push(parkJson);
            itemobj.parkVipList = data.data;
            itemobjArr.push(itemobj);
          }
        });
      }
      self.mouthTicketData.dataSave.parkJson = parkJsonArr;
      self.tableData.parkItems = itemobjArr;
    },
    delectSelectParkItem(index, parkId) {
      var _this = this;
      _this.tableData.parkItems.splice(index, 1);
      _this.mouthTicketData.dataSave.parkJson.splice(index, 1);
    },
    submitForm(formName) {
      var self = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          self.saveTicket();
        } else {
          return false;
        }
      });
    },
    modifyVisitor(visitor) {
      var self = this;
      self.traderstatus = 'edit';
      self.actionStatus = 'edit';
      self.remarkChunkShow = false;
      this.entity.id = visitor.id;
      this.editVisitor(visitor.id, 'edit');
    },
    formatTime(value) {
      //value为13位的时间戳
      function addzero(m) {
        return m < 10 ? '0' + m : m;
      }
      var time = new Date(parseInt(value));
      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      var shi = time.getHours();
      var fen = time.getMinutes();
      var miao = time.getSeconds();
      if (value) {
        return y + '-' + addzero(m) + '-' + addzero(d) + ' ' + addzero(shi) + ':' + addzero(fen) + ':' + addzero(miao);
      }
    },
    editVisitor(visitorId, type) {
      var self = this;
      var params = {};
      self.mouthTicketData.isCreate = false;
      params.parkVisitorlistId = visitorId;
      self.resetMouthData();
      API.park.parkVisitorlistDetail(params).then(
        res => {
          var data = res;
          // 转化时间戳
          var visitFrom = self.formatTime(data.data.visitFrom);
          var visitTo = self.formatTime(data.data.visitTo);
          self.mouthTicketData.dataSave.id = data.data.id;
          self.mouthTicketData.dataSave.carLicenseNumber = data.data.carLicenseNumber;
          self.mouthTicketData.dataSave.owner = data.data.owner;
          self.mouthTicketData.dataSave.ownerPhone = data.data.ownerPhone;
          self.mouthTicketData.dataSave.visitReason = data.data.visitReason;
          self.mouthTicketData.dataSave.remark1 = data.data.remark1;
          self.mouthTicketData.dataSave.remark2 = data.data.remark2;
          self.mouthTicketData.dataSave.remark3 = data.data.remark3;

          self.mouthTicketData.dataSave.visitFromTo = [new Date(visitFrom), new Date(visitTo)];

          self.entity.parkList = [];
          for (var i = 0; i < data.data.parkList.length; i++) {
            self.tableData.ParkNameList.push(data.data.parkList[i].parkName);
            self.entity.parkList.push(data.data.parkList[i].parkId);
            self.tableData.parkIdList.push(data.data.parkList[i].parkId);
            self.tableData.parkVipTypeId.push(data.data.parkList[i].parkVipTypeId);
          }
          self.specialCarTypeConfigName = data.data.specialCarTypeConfigName;
          self.mouthTicketData.dataSave.specialCarTypeConfigId = data.data.specialCarTypeConfigId;
          self.toOpenModal('createVisitorModal');
        },
        err => {}
      );
    },
    saveTicket() {
      var self = this;
      var params = deepCopyObj(self.mouthTicketData.dataSave);
      if (params['visitFromTo'] == '') {
        self.showToast('请选择可销售时间', 0);
        return;
      }
      params['visitFrom'] = self.mouthTicketData.dataSave.visitFromTo[0].Format('yyyy-MM-dd hh:mm:ss');
      params['visitTo'] = self.mouthTicketData.dataSave.visitFromTo[1].Format('yyyy-MM-dd hh:mm:ss');

      let url = self.traderstatus == 'new' ? '/park/parkVisitorlist/save.do' : '/park/parkVisitorlist/edit.do'
      API.fetchPost(url,params).then(
        res => {
          var data = res;
          if (data.status == 1) {
            if (self.traderstatus == 'new') {
              self.showToast('访客车辆创建成功', 1);
            } else {
              self.showToast('访客车辆修改成功', 1);
            }
            self.closed('createVisitorModal');
            self.getList();
          } else {
            self.showToast(data.message, 2);
          }
        },
        err => {}
      );
    },
    delVisitor(ticket) {
      var self = this;
      var params = {
        parkVisitorlistId: ticket.id
      };
      self.showDialog('确认删除该访客车辆?', '', function() {
        API.park.parkVisitorlistDel(params).then(
          res => {
            //start
            var data = res;
            self.showToast('删除访客车辆成功', 1);
            self.getList();
            //end
          },
          err => {}
        );
      });
    }, //del ticket end

    //导出数据
    exportData() {
      let self = this;
      let theadsArr = [];
      for (let i = 0; i < self.theadsInfo.length; i++) {
        if (self.theadsInfo[i].checked) {
          theadsArr.push(self.theadsInfo[i].prop);
        }
      }
      let params = {
        meterList: theadsArr.join(',')
      };
      params = $.extend({}, params, this.searchParams, this.otherParams);
      self.showDialog('确认导出该报表?', '', function() {
        self.toExportAsync('/park/parkVisitorlist/exportVisitorlist.do', params);
      });
    }, //end 导出数据

    syncDetail(monthTicketBillDetailId, open) {
      var self = this;
      self.syncDetailModal.syncDetailList = [];
      let params = {
        parkVisitorlistId: monthTicketBillDetailId
      };
      API.park.parkVisitorlistFindSyncDetail(params).then(
        res => {
          let data = res.data;
          self.syncDetailModal.syncDetailList = data;
          if (open) {
            self.toOpenModal('syncDetailModal');
          }
        },
        err => {}
      );
    },
    reSync(syncDetail) {
      var self = this;
      let params = {
        id: syncDetail.id
      };
      API.park.parkVisitorlistResync(params).then(
        res => {
          self.syncDetail(syncDetail.parkVisitorlistId);
          self.showToast('重新同步成功', false);
        },
        err => {}
      );
    }
  },
  filters: {
    sendStatus: function(val) {
      switch (val) {
        case 0:
          return '未发送';
        case 1:
          return '发送中';
        case 2:
          return '同步成功';
        case 3:
          return '同步失败';
        default:
          break;
      }
    }
  }
};
